<?php
require_once '../vendor/autoload.php';

use Workerman\Worker;
use Workerman\Lib\Timer;
use PHPSocketIO\SocketIO;

require_once './SingleMysql.php';
require_once './SingleRedis.php';

$asr_socketio = new SocketIO(12120);
$mysql = SingleMysql::getInstance();
//$redis = SingleRedis::getInstance();
$config = require './config.php';
$redis = new Redis();
$redis->connect($config['redis']['db_host'], $config['redis']['db_port']);
//为了让超时的服务永不超时？有用吗
$redis->setOption(Redis::OPT_READ_TIMEOUT, -1);
//开始
$asr_socketio->on('workerStart', function () use ($asr_socketio) {

});

//事件
$asr_socketio->on('connection', function ($socket) use ($asr_socketio) {
       //转写端链接 后发送消息
       $socket->on('send audio info', function ($data) use ($socket, $asr_socketio) {
        try {
            global $mysql, $redis;
            //校验数据
            $transfer_data = json_decode($data, true);
            if (!$transfer_data) {
                //如果数据格式不正确，返回错误信息
                $socket->emit('receive state', '{code:201,message:"数据格式不正确",type:"send audio info"}');
                return;
            }
            //给语音服务器发送接收状态
            $socket->emit('receive state', '{code:200,message:"success",type:"send audio info"}');
            //获取meetingid
            $mid = $transfer_data['meeting_id'];
            //获取meeting对应表的lid
            $lid = $redis->hGet('meeting_to_lid', $mid);
            //判断meeting是否储存在对应表id的hash中
            if (!$lid) {
                //如果不存在则 查找并添加入hash
                $lid = $mysql->select('id')->from('rszh_meeting_live_speech')->where('meeting_tag = :mid')->bindValues(['mid' => $mid])->query();
                //如果不在数据库，则return
                if (empty($lid)) {
                    $socket->emit('receive state', '{code:202,message:"未找到meetingid",type:"send audio info"}');
                    return;
                }
                $lid = $lid[0]['id'];
                $redis->hSet('meeting_to_lid', $mid, $lid);
            }
            //数据处理
            $transfer = [
                'or_txt' => $transfer_data['raw_text'],
                'ed_txt' => '',
                'url' => $transfer_data['url'],
                'paly_time' => $transfer_data['pcmtime'],
                'status' => $transfer_data['end_of_speech'],
                'timestamp' => $transfer_data['timestamp']
                //'sorting' => $sorting + 0,
            ];
            //初始化
            $sorting = 1;
            //查看储存该转写结果的状态是否存在
            if (!$redis->hGet($mid . "_state", 'lower')) {
                //不存在则 创建string储存结果状态
                //string
                $redis->hMSet($mid . "_state", ['subsection' => 0, 'lower' => $sorting, 'editstate' => 0, 'lastTime' => 0]);
                $redis->expire($mid . "_state", 60 * 60 * 24);
                //上传web
            } else {
                //如果存在则判断end_of_speech是否为1
                if ($transfer_data['end_of_speech']) {
                    //获取当前排序
                    $sorting = $redis->hGet($mid . "_state", 'lower');
                    //修改meeting_state
                    $redis->hSet($mid . "_state", 'lower', $sorting + 1);
                    $redis->expire($mid . "_state", 60 * 60 * 24);
                    //该句结束，则储存hash
                    $transfer['sorting'] = $sorting;
                    //排序准备 redis中加入新字段 end_of_speech为1则向lastTime加入该句的时间戳
                    $redis->hSet($mid . "_state", 'lastTime', $transfer['timestamp']);
                    $transfer['sc'] = $redis->hGet($mid . "_state", 'subsection');
                    //hash
                    $redis->hSet($mid, $sorting, json_encode($transfer, JSON_UNESCAPED_UNICODE));
                    //$redis->hSet($mid, $sorting, json_encode($transfer));
                    $redis->expire($mid, 60 * 60 * 24);
                    //并且存入数据库
                    $save = [
                        "lid" => $lid,
                        "transfer" => $transfer['or_txt'],
                        "editor" => $transfer['ed_txt'],
                        "url" => $transfer['url'],
                        "pcmtime" => $transfer['paly_time'] . '',
                        "sorting" => $sorting + 0,
                        "subsection" => $transfer['sc'],
                        "create_time" => time()
                    ];
                    //判断是否成功以后加
                    $lid = $mysql->insert('rszh_meeting_convert')->cols($save)->query();
                }
                //如果存在end_of_speech为0
                else {
                    //获取当前排序
                    $sorting = $redis->hGet($mid . "_state", 'lower');
                    $transfer['sorting'] = $sorting;
                    //获取当前结果hash中对应的数据
                    $result_json = $redis->hGet($mid, $sorting);
                    //判断当前结果数据和新上传的值是否相同
                    if ($result_json) {
                        $result = json_decode($result_json, true);
                        if ($result['or_txt'] == $transfer['or_txt']) {
                            return;
                        }
                        $transfer['sc'] = $redis->hGet($mid . "_state", 'subsection');
                    } else {
                        //如果没有数据说明是新的一句 那么判断时间
                        $lasttime = $redis->hGet($mid . "_state", 'lastTime');
                        if ($lasttime) {
                            //如果时间大于4秒，则分段
                            if ($transfer['timestamp'] >= $lasttime + 4) {
                                //分段 
                                $br = [
                                    'or_txt' => '<br>',
                                    'ed_txt' => '',
                                    'url' => '',
                                    'paly_time' => 0,
                                    'status' => 1,
                                    'timestamp' => '',
                                    'sc' => $redis->hGet($mid . "_state", 'subsection')
                                    //'sorting' => $sorting + 0,
                                ];
                                //$asr_socketio->to($mid)->emit('get audio info', $br);
                                $redis->lPush('transferMQ',json_encode(['transfer' => $br, 'mid' => $transfer_data['meeting_id']], JSON_UNESCAPED_UNICODE));
                                $transfer['sc'] = $redis->hIncrBy($mid . "_state", 'subsection', 1);
                                $redis->hSet($mid . "_state", 'lastTime', 0);
                            } else {
                                $transfer['sc'] = $redis->hGet($mid . "_state", 'subsection');
                            }
                        }
                    }
                    //如果值不同，存入结果hash
                    $redis->hSet($mid, $sorting, json_encode($transfer, JSON_UNESCAPED_UNICODE));
                    //$redis->hSet($mid, $sorting, json_encode($transfer));
                    $redis->expire($mid, 60 * 60 * 24);
                }
            }
            //传给web
            //$asr_socketio->to($mid)->emit('get audio info', $transfer);
            $mq_push = [
                'transfer' => $transfer,
                'mid' => $transfer_data['meeting_id']
            ];
            $redis->lPush('transferMQ',json_encode($mq_push, JSON_UNESCAPED_UNICODE));
            //  if($mid == '2019052134') {
            //     return;
            // }
            //$socket->broadcast->emit('get audio info', $transfer);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    });

    //加密狗功能测试
    $socket->on('send soft dog info', function ($msg) use ($socket) {
        try {
            global $mysql, $redis;
            //echo $msg . "\n";
            $msg = json_decode($msg, true);
            if (!$msg) {
                $socket->emit('receive state', '{code:201,message:"数据格式不正确",type:"send soft dog info"}');
                return;
            }
            //储存加密狗设置
            $result = $redis->hMSet('soft_dog', ['key_id' => $msg['key_id'], 'product_name' => $msg['product_name'], 'soft_dog' => $msg['soft_dog'], 'update_time' => time()]);
            //储存到数据库
            $is_exist = $mysql->select("*")->from('rszh_soft_dog')->where('id= :id')->bindValues(array('id' => 1))->row();
            if ($is_exist) {
                $quary = "UPDATE `rszh_soft_dog` SET `key`=" . "'" . $msg['key_id'] . "'" . ",`name`=" . "'" . $msg['product_name'] . "'" . ",`brand`=" . "'" . $msg['soft_dog'] . "'" . ",`update_time`=" . "'" . time() . "'" . " WHERE ID=1";
                $mr = $mysql->query($quary);
            } else {
                $quary = "INSERT INTO `rszh_soft_dog` (`key`,`name`,`brand`,`create_time`,`update_time`) VALUES (" . "'" . $msg['key_id'] . "'" . "," . "'" . $msg['product_name'] . "'" . "," . "'" . $msg['soft_dog'] . "'" . "," . "'" . time() . "'" . "," . "'" . time() . "'" . ")";
                $mr = $mysql->query($quary);
            }
            if ($result) {
                $socket->emit('receive state', '{code:200,message:"success",type:"send soft dog info"}');
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    });
});

header("ALLOW-CONTROL-ALLOW-ORIGIN:*");
// 如果不是在根目录启动，则运行runAll方法
if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}
